import numpy as np
import os, imageio


########## Slightly modified version of LLFF data loading code 
##########  see https://github.com/Fyusion/LLFF for original

def _minify(basedir, factors=[], resolutions=[]):
    needtoload = False
    for r in factors:
        imgdir = os.path.join(basedir, 'images_{}'.format(r))
        if not os.path.exists(imgdir):
            needtoload = True
    for r in resolutions:
        imgdir = os.path.join(basedir, 'images_{}x{}'.format(r[1], r[0]))
        if not os.path.exists(imgdir):
            needtoload = True
    if not needtoload:
        return
    
    from shutil import copy
    from subprocess import check_output
    
    imgdir = os.path.join(basedir, 'images')
    imgs = [os.path.join(imgdir, f) for f in sorted(os.listdir(imgdir))]
    imgs = [f for f in imgs if any([f.endswith(ex) for ex in ['JPG', 'jpg', 'png', 'jpeg', 'PNG']])]
    imgdir_orig = imgdir
    
    wd = os.getcwd()

    for r in factors + resolutions:
        if isinstance(r, int):
            name = 'images_{}'.format(r)
            resizearg = '{}%'.format(100./r)
        else:
            name = 'images_{}x{}'.format(r[1], r[0])
            resizearg = '{}x{}'.format(r[1], r[0])
        imgdir = os.path.join(basedir, name)
        if os.path.exists(imgdir):
            continue
            
        print('Minifying', r, basedir)
        
        os.makedirs(imgdir)
        check_output('cp {}/* {}'.format(imgdir_orig, imgdir), shell=True)
        
        ext = imgs[0].split('.')[-1]
        args = ' '.join(['mogrify', '-resize', resizearg, '-format', 'png', '*.{}'.format(ext)])
        print(args)
        os.chdir(imgdir)
        check_output(args, shell=True)
        os.chdir(wd)
        
        if ext != 'png':
            check_output('rm {}/*.{}'.format(imgdir, ext), shell=True)
            print('Removed duplicates')
        print('Done')
            
        
        
        
def _load_data(basedir, factor=None, width=None, height=None, load_imgs=True):
    
    poses_arr = np.load(os.path.join(basedir, 'poses_bounds.npy'))  # 20 x 17
    # 20 is the number of frames  
    poses = poses_arr[:, :-2].reshape([-1, 3, 5]).transpose([1,2,0])  # 3 x 5 x 20 
    # poses[:, :4, :] 是Camera-to-world transformation matrix, shape [3, 4] 即[R|T]外参矩阵
    # poses[:, 4, :] 是 H, W, focal length
    bds = poses_arr[:, -2:].transpose([1,0]) # 2 x 20 
    # 近边界与原边界, shape [2]
    img0 = [os.path.join(basedir, 'images', f) for f in sorted(os.listdir(os.path.join(basedir, 'images'))) \
            if f.endswith('JPG') or f.endswith('jpg') or f.endswith('png')][0] # get the first image 
    sh = imageio.imread(img0).shape # 3024 x 4032 x 3 
    
    sfx = ''
    
    if factor is not None:
        sfx = '_{}'.format(factor)
        _minify(basedir, factors=[factor])
        factor = factor
    elif height is not None:
        factor = sh[0] / float(height)
        width = int(sh[1] / factor)
        _minify(basedir, resolutions=[[height, width]])
        sfx = '_{}x{}'.format(width, height)
    elif width is not None:
        factor = sh[1] / float(width)
        height = int(sh[0] / factor)
        _minify(basedir, resolutions=[[height, width]])
        sfx = '_{}x{}'.format(width, height)
    else:
        factor = 1
    
    # 加载下采样1/4的图像 
    imgdir = os.path.join(basedir, 'images' + sfx)
    if not os.path.exists(imgdir):
        print( imgdir, 'does not exist, returning' )
        return
    
    imgfiles = [os.path.join(imgdir, f) for f in sorted(os.listdir(imgdir)) if f.endswith('JPG') or f.endswith('jpg') or f.endswith('png')]
    if poses.shape[-1] != len(imgfiles):
        print( 'Mismatch between imgs {} and poses {} !!!!'.format(len(imgfiles), poses.shape[-1]) )
        return
    
    # 更换分辨率，如果换用下采样的图像，则需要更换分辨率
    sh = imageio.imread(imgfiles[0]).shape # 756 x 1008 x 3 
    poses[:2, 4, :] = np.array(sh[:2]).reshape([2, 1]) # 将图像的高宽信息存储到poses中
    poses[2, 4, :] = poses[2, 4, :] * 1./factor # 将图像的焦距信息存储到poses中
    
    if not load_imgs:
        return poses, bds
    
    def imread(f):
        if f.endswith('png'):
            return imageio.imread(f, ignoregamma=True)
        else:
            return imageio.imread(f)
        
    imgs = imgs = [imread(f)[...,:3]/255. for f in imgfiles]
    imgs = np.stack(imgs, -1)  
    
    print('Loaded image data', imgs.shape, poses[:,-1,0])
    return poses, bds, imgs
    # poses shape [3, 5, N] 5的前四个是R|T,即R_X|R_Y|R_Z|T， 最后一个是H, W, focal length
    # bds shape [2, N] 近边界与原边界, shape [2]            
    

def normalize(x):
    return x / np.linalg.norm(x)

def viewmatrix(z, up, pos):
    # input shapes are both [3]
    vec2 = normalize(z) # in fact, this has normalized before 
    vec1_avg = up
    vec0 = normalize(np.cross(vec1_avg, vec2)) # 叉乘 # return a vector perpendicular to vec1 and vec2
    vec1 = normalize(np.cross(vec2, vec0)) # 叉乘 # return a vector perpendicular to vec2 and vec0
    m = np.stack([vec0, vec1, vec2, pos], 1) # shape is [3, 4]
    return m

def ptstocam(pts, c2w):
    tt = np.matmul(c2w[:3,:3].T, (pts-c2w[:3,3])[...,np.newaxis])[...,0]
    return tt

def poses_avg(poses): # poses shape [20, 3, 5]
    # R is Y(-X)Z

    hwf = poses[0, :3, -1:] # height, width, focal length # shape [3, 1]

    center = poses[:, :3, 3].mean(0) # 3 is T transpose matrix # average center # shape [3]
    vec2 = normalize(poses[:, :3, 2].sum(0)) # poses[:, :3, 2] is z rotation matrix # average z rotation matrix # result shape is [3]
    up = poses[:, :3, 1].sum(0) # is -x rotation matrix  # result shape is [3]
    c2w = np.concatenate([viewmatrix(vec2, up, center), hwf], 1) # viewmatrix return a 3x4 matrix, normal_x, normal_y, normal_z, center # shape is [3, 4]
    
    return c2w # a average camera to world transformation matrix # shape is [3, 5]



def render_path_spiral(c2w, up, rads, focal, zdelta, zrate, rots, N):
    render_poses = []
    rads = np.array(list(rads) + [1.])
    hwf = c2w[:,4:5]
    
    for theta in np.linspace(0., 2. * np.pi * rots, N+1)[:-1]:
        c = np.dot(c2w[:3,:4], np.array([np.cos(theta), -np.sin(theta), -np.sin(theta*zrate), 1.]) * rads) 
        z = normalize(c - np.dot(c2w[:3,:4], np.array([0,0,-focal, 1.])))
        render_poses.append(np.concatenate([viewmatrix(z, up, c), hwf], 1))
    return render_poses
    


def recenter_poses(poses): # poses shape [20, 3, 5]

    poses_ = poses+0 # copy
    bottom = np.reshape([0,0,0,1.], [1,4]) # is [[0. 0. 0. 1.]] # shape is [1, 4]
    c2w = poses_avg(poses) # get a average camera to world transformation matrix # shape is [3, 5]
    c2w = np.concatenate([c2w[:3,:4], bottom], -2) # [3, 4] concat [1, 4] -> [4, 4] # concat a bottom row 
    bottom = np.tile(np.reshape(bottom, [1,1,4]), [poses.shape[0],1,1]) # tile a bottom row # shape is [20, 1, 4]
    poses = np.concatenate([poses[:,:3,:4], bottom], -2) # [20, 3, 4] concat [20, 1, 4] -> [20, 4, 4] # concat a bottom row
    # now the c2w is [4, 4] and poses is [20, 4, 4]

    poses = np.linalg.inv(c2w) @ poses # inverse c2w is a new world axis # we get the new poses (new camera to world transformation matrix)
    poses_[:,:3,:4] = poses[:,:3,:4] # :3 throw the bottom row  # replace the old poses with the new poses, keep the hwf
    poses = poses_
    return poses


#####################


def spherify_poses(poses, bds):
    
    p34_to_44 = lambda p : np.concatenate([p, np.tile(np.reshape(np.eye(4)[-1,:], [1,1,4]), [p.shape[0], 1,1])], 1)
    
    rays_d = poses[:,:3,2:3] # R_z direction, shape is [20, 3, 1] # 所有摄像机坐标系的Z轴在世界坐标系中的向量
    rays_o = poses[:,:3,3:4] # T origin, shape is [20, 3, 1] # 所有摄像机坐标系的原点在世界坐标系中的坐标

    def min_line_dist(rays_o, rays_d):
        A_i = np.eye(3) - rays_d * np.transpose(rays_d, [0,2,1]) # shape is [20, 3, 3]
        b_i = -A_i @ rays_o # shape is [20, 3, 1]
        pt_mindist = np.squeeze(-np.linalg.inv((np.transpose(A_i, [0,2,1]) @ A_i).mean(0)) @ (b_i).mean(0))
        return pt_mindist # shape is [3]

    pt_mindist = min_line_dist(rays_o, rays_d) # shape is [3]
    
    center = pt_mindist # shape is [3] # 新的世界坐标系原点
    up = (poses[:,:3,3] - center).mean(0) # shape is [3]

    vec0 = normalize(up) # shape is [3]
    vec1 = normalize(np.cross([.1,.2,.3], vec0)) # shape is [3]
    vec2 = normalize(np.cross(vec0, vec1)) # shape is [3]
    pos = center # shape is [3]
    c2w = np.stack([vec1, vec2, vec0, pos], 1) # shape is [3, 4] # 新的世界坐标系

    poses_reset = np.linalg.inv(p34_to_44(c2w[None])) @ p34_to_44(poses[:,:3,:4]) # shape is [20, 4, 4]

    rad = np.sqrt(np.mean(np.sum(np.square(poses_reset[:,:3,3]), -1))) # shape is [1]
    
    sc = 1./rad # 放缩到单位球上
    poses_reset[:,:3,3] *= sc
    bds *= sc
    rad *= sc # 1.0
    
    centroid = np.mean(poses_reset[:,:3,3], 0) # shape is [3]
    zh = centroid[2] # shape is [1] # 摄像机平均高度
    radcircle = np.sqrt(rad**2-zh**2) # shape is [1] # 在平均高度下的半径 # 之后会在这个小圆上采样渲染路径
    new_poses = []
    
    # 获取渲染路径
    for th in np.linspace(0.,2.*np.pi, 120): # from 0 to 2pi, 120 points

        camorigin = np.array([radcircle * np.cos(th), radcircle * np.sin(th), zh]) # shape is [3]
        up = np.array([0,0,-1.]) # shape is [3]

        vec2 = normalize(camorigin) # shape is [3]
        vec0 = normalize(np.cross(vec2, up)) # shape is [3]
        vec1 = normalize(np.cross(vec2, vec0)) # shape is [3]
        pos = camorigin # shape is [3]
        p = np.stack([vec0, vec1, vec2, pos], 1) # shape is [3, 4]

        new_poses.append(p)

    new_poses = np.stack(new_poses, 0) # shape is [120, 3, 4]
    
    new_poses = np.concatenate([new_poses, np.broadcast_to(poses[0,:3,-1:], new_poses[:,:3,-1:].shape)], -1) # shape is [120, 3, 5]
    poses_reset = np.concatenate([poses_reset[:,:3,:4], np.broadcast_to(poses[0,:3,-1:], poses_reset[:,:3,-1:].shape)], -1) # shape is [120, 3, 5]
    
    return poses_reset, new_poses, bds # new_poses is rendered poses, poses_reset is the new camera to world transformation matrix, bds is the new bounding box
    

def load_llff_data(basedir, factor=8, recenter=True, bd_factor=.75, spherify=False, path_zflat=False):
    

    poses, bds, imgs = _load_data(basedir, factor=factor) # factor=8 downsamples original imgs by 8x
    print('Loaded', basedir, bds.min(), bds.max())
    
    # Correct rotation matrix ordering and move variable dim to axis 0
    # pose origin shape is [3, 5, N]
    # poses[:, 0:1, :] 是R_x
    # poses[:, 1:2, :] 是R_Y
    # poses[:, 2:3, :] 是R_Z
    # poses[:, 3:4, :] 是T
    poses = np.concatenate([poses[:, 1:2, :], -poses[:, 0:1, :], poses[:, 2:, :]], 1) # 将XYZ转换到Y(-X)Z
    # 以下，将N移到第一维
    poses = np.moveaxis(poses, -1, 0).astype(np.float32) # 20 * 3 * 5 # 3, -1 hwf  # 将N移到第一维
    imgs = np.moveaxis(imgs, -1, 0).astype(np.float32)
    images = imgs
    bds = np.moveaxis(bds, -1, 0).astype(np.float32) # 20 * 2
    
    # Rescale if bd_factor is provided
    sc = 1. if bd_factor is None else 1./(bds.min() * bd_factor)
    # poses origin shape is [20, 3, 5]
    poses[:,:3,3] *= sc # 将T缩放到bd_factor # R不需要缩放，因为R是单位矩阵
    bds *= sc # 将bds缩放到bd_factor
    
    if recenter:
        # poses origin shape is [20, 3, 5] 
        poses = recenter_poses(poses) # 重设世界坐标系的原点到相机平均坐标点
        
    if spherify:
        poses, render_poses, bds = spherify_poses(poses, bds)

    else: # 如果不采用球面投影，则把相机坐标系的原点移到相机平均坐标点
        
        c2w = poses_avg(poses)
        print('recentered', c2w.shape)
        print(c2w[:3,:4])

        ## Get spiral
        # Get average pose
        up = normalize(poses[:, :3, 1].sum(0))

        # Find a reasonable "focus depth" for this dataset
        close_depth, inf_depth = bds.min()*.9, bds.max()*5.
        dt = .75
        mean_dz = 1./(((1.-dt)/close_depth + dt/inf_depth)) # 平均深度 # '1.' is '1.0'
        focal = mean_dz

        # Get radii for spiral path
        shrink_factor = .8 
        zdelta = close_depth * .2 
        tt = poses[:,:3,3] # ptstocam(poses[:3,3,:].T, c2w).T # 平移矩阵 [20, 3]
        rads = np.percentile(np.abs(tt), 90, axis=0) # 求90%百分位数 [3] # 获得90%的深度包括X,Y,Z三个方向
        c2w_path = c2w
        N_views = 120
        N_rots = 2
        if path_zflat:
#             zloc = np.percentile(tt, 10, 0)[2]
            zloc = -close_depth * .1
            c2w_path[:3,3] = c2w_path[:3,3] + zloc * c2w_path[:3,2]
            rads[2] = 0.
            N_rots = 1
            N_views/=2

        # Generate poses for spiral path # 得到螺旋路径的pose # up is [3]
        render_poses = render_path_spiral(c2w_path, up, rads, focal, zdelta, zrate=.5, rots=N_rots, N=N_views) 
        
        
    render_poses = np.array(render_poses).astype(np.float32)

    c2w = poses_avg(poses)
    print('Data:')
    print(poses.shape, images.shape, bds.shape)
    
    dists = np.sum(np.square(c2w[:3,3] - poses[:,:3,3]), -1) # 计算每个摄像机到摄像机平均坐标点的距离
    i_test = np.argmin(dists) # 找到距离最近的摄像机 # 作为测试集
    print('HOLDOUT view is', i_test) 
    
    images = images.astype(np.float32)
    poses = poses.astype(np.float32)

    return images, poses, bds, render_poses, i_test



